package com.powernode.shop.controller;

import com.powernode.shop.domain.SysMenu;
import com.powernode.shop.service.SysMenuService;
import com.powernode.shop.vo.MenuAndAuthVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/10
 */

@RestController
@RequestMapping("/sys/menu")
public class MenuController {

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 加载菜单
     * @return  使用spring自带的统一返回json
     */
    @GetMapping("/nav")
    public ResponseEntity<MenuAndAuthVo> loadMenuAndAuth(){
        // 权限上下文得到实体id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userId = authentication.getPrincipal().toString();
        List<SysMenu> sysMenuList = sysMenuService.loadMenuByUserId(userId);
        // 得到权限字符串对象 变为 字符串集合
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> authorityStrList = authorities.stream().map(Object::toString).collect(Collectors.toList());
        MenuAndAuthVo menuAndAuthVo = new MenuAndAuthVo(sysMenuList, authorityStrList);
        return ResponseEntity.ok(menuAndAuthVo);
    }

}
